package org.vacoor.xqq.ui.comp.combo;

import org.vacoor.nothing.ui.util.UIs;

import javax.swing.*;
import javax.swing.plaf.basic.BasicComboBoxEditor;
import java.awt.*;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;

/**
 * 输入框
 */
public class IconifyComboBoxEditor extends BasicComboBoxEditor {
    private static final Font FONT = UIs.getBestFont();
    private JPanel editorPanel;
    private JLabel label;

    public IconifyComboBoxEditor() {
        super();
        init();
    }

    private void init() {
        label = createEditorLabel();
        editorPanel = createEditorPanel();

        editorPanel.setLayout(new BorderLayout(0, 0));
        editorPanel.add(label, BorderLayout.WEST);
        editorPanel.add(editor, BorderLayout.CENTER);
    }

    @Override
    public Component getEditorComponent() {
        return editorPanel;
    }

    public JTextField getInnerTextField() {
        return editor;
    }

    @Override
    protected JTextField createEditorComponent() {
        JTextField editor = super.createEditorComponent();
        editor.setOpaque(false);
        editor.setBorder(BorderFactory.createEmptyBorder(3, 5, 3, 5));
        editor.setFont(FONT);
        return editor;
    }

    protected JLabel createEditorLabel() {
        JLabel label = new JLabel();
        label.setOpaque(false);
        label.setBorder(BorderFactory.createEmptyBorder(3, 3, 3, 0));
        return label;
    }

    protected JPanel createEditorPanel() {
        final JPanel editorPanel = new JPanel();
        editorPanel.setRequestFocusEnabled(false);
        editorPanel.setFocusable(false);
        editorPanel.setBorder(null);
        editorPanel.setBackground(Color.WHITE);
        editorPanel.addComponentListener(new ComponentAdapter() {
            @Override
            public void componentResized(ComponentEvent e) {
                if (editor != null) {
                    editor.setFont(editor.getFont().deriveFont(editorPanel.getHeight() - 10F));
                }
            }
        });
        return editorPanel;
    }

    /**
     * 选择时调用该方法
     *
     * @param anObj
     */
    @Override
    public void setItem(Object anObj) {
        super.setItem(anObj);
        /*
        if (anObj == null || !(anObj instanceof IconifyComboItem)) {
            return;
        }
        IconifyComboItem item = (IconifyComboItem) anObj;
        ImageIcon ico = (ImageIcon) item.getIcon();
        label.setIcon(ico == null ? ico : new ImageIcon(ImageUtil.resize(ico.getImage(), new Dimension(20, 20))));
        */
    }

    /**
     * 当编辑时会调用该方法
     *
     * @return
     */
    @Override
    public Object getItem() {
        return super.getItem();
    }
}
